﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace WebAPI测试程序.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            if(context.ExceptionHandled == false)
            {
                // 开始处理异常
                // Console.WriteLine($"开始处理异常: {context.Exception.Message}");
                logger.LogError($"开始处理异常: {context.Exception.Message}");

                // 定义执行结果
                context.Result = new JsonResult(new
                {
                    ContentType = "application/json",
                    StatusCode = HttpStatusCode.InternalServerError,
                    Content = context.Exception.Message
                });

                context.ExceptionHandled = true;
            }
        }
    }
}
